#include "PrismaticZ.h"
#include "RigidBodyNode.h"
#include "Mat6x6.h"
#include "PrescribedMotion.h"
#include "EOMData.h"
#include "ABAData.h"

using namespace RSIM;
using namespace std;

///////////////////////////////////////////////////////

int PrismaticZ::getJointDOF()const{return 1;}

///////////////////////////////////////////////////////

void PrismaticZ::calc_H_x_UDot(const State& state, double *h_x_udot) const{
	h_x_udot[5] = state.getUDotForNode(this->NodeIndex_)[0];
}

///////////////////////////////////////////////////////

void PrismaticZ::setDefaultQ(double *q)const{
	q[0] = 0.0;	
}

///////////////////////////////////////////////////////

void PrismaticZ::setDefaultU(double *u)const{
	u[0] = 0.0;
}

///////////////////////////////////////////////////////

void PrismaticZ::calcQDot(State& state)const{
	state.wgetQDotForNode(this->NodeIndex_)[0] = state.getUForNode(this->NodeIndex_)[0];
}

///////////////////////////////////////////////////////

void PrismaticZ::updRelVelocity(const State& state, Vect3& w, Vect3& v)const{
	v(2) = state.getUForNode(this->NodeIndex_)[0];
}

///////////////////////////////////////////////////////

PrismaticZ::PrismaticZ(const int& NodeIndex):Joint(PrismaticZJoint){
	this->NodeIndex_ = NodeIndex;
}

///////////////////////////////////////////////////////

PrismaticZ* PrismaticZ::New(const int& NodeIndex){
	return new PrismaticZ(NodeIndex);
}

///////////////////////////////////////////////////////

void PrismaticZ::printJointType() const{
	cout<<"Joint Type=PrismaticZ\n";
}

///////////////////////////////////////////////////////

void PrismaticZ::updJointTransform(	const double *q,
						const RigidBodyNode *Parent,
						const int& pChildID,
						double *betak){
	double tmp[] = {0.0,0.0,q[0]};
	this->T_MF_.wgetP().copy(tmp);
	
	this->updBetaK(q,Parent,pChildID,betak);
}

///////////////////////////////////////////////////////

void PrismaticZ::updBetaK(const double *q,
				 const RigidBodyNode *Parent,
				 const int& pChildID,
				 double *betak)const{
	if(Parent){
		// Calculate betak in F basis of parent
		const double *T_FM_P_Ptr = Parent->data_->getBodyTransformFM()[pChildID].P().Ptr();
		const double *T_FM_R_Ptr = Parent->data_->getBodyTransformFM()[pChildID].R().Ptr();
		
		betak[0]=T_FM_P_Ptr[0];
		betak[1]=T_FM_P_Ptr[1];
		betak[2]=T_FM_P_Ptr[2];

		betak[0] += T_FM_R_Ptr[2]*q[0];
		betak[1] += T_FM_R_Ptr[5]*q[0];
		betak[2] += T_FM_R_Ptr[8]*q[0];
	}
}

///////////////////////////////////////////////////////

void PrismaticZ::updVelocity(const State& state, 
				    const RigidBodyNode *Parent,
				    const Rotation& prF_C_F, 
				    const double *betak,
				    Vect3& w,
				    Vect3& v) const {
					    
	const Vect3& pr_w = Parent->data_->getAngularVelocity();
	const Vect3& pr_v = Parent->data_->getLinearVelocity();
	
	// 1. F_C_prF*pr_w is the absolute angular velocity
	// of the parent expressed in the joint's F frame
	double *wptr = w.wPtr();
	FastOps::transpose_mult_mat33_vec3(prF_C_F.Ptr(),pr_w.Ptr(),wptr);
	
	double v_tmp[3];
	
	// omega x r
	FastOps::cross(pr_w.Ptr(),betak,v_tmp);
	
	// v + omega x r
	v_tmp[0] += pr_v(0);
	v_tmp[1] += pr_v(1);
	v_tmp[2] += pr_v(2);
	
	// convert v + omega x r to F basis of this body
	FastOps::transpose_mult_mat33_vec3(prF_C_F.Ptr(), v_tmp, v.wPtr());
	
	// Velocity = v + omega x r + qdot
	v.wPtr()[2] += state.getUForNode(this->NodeIndex_)[0];
}

///////////////////////////////////////////////////////

void PrismaticZ::calcAKT(	const RigidBodyNode *Parent, 
				const RigidBodyNode *Body,
				const int& ChildID,
				const double *betak,
				State& state,
				Vect6& sAkt) const{	
	this->calcQDot(state);
	double *UDot = state.wgetUDotForNode(this->NodeIndex_);
	
	if(Parent){		
		const double *U = state.getUForNode(this->NodeIndex_);
	
		// AKT is calculated in F basis of this body
		double *akt_ptr = sAkt.wPtr();
		
		// set Akt to zero to clear existing values.
		akt_ptr[0] = 0.0;akt_ptr[1] = 0.0;akt_ptr[2] = 0.0;
		
		const double *prFCF_Ptr = Body->data_->getRotationFCF().Ptr();
		
		double s_betak[3], ang_vel[3];
		
		// Angular velocity of parent expressed in F of parent
		const double *parent_ang_ptr = Parent->data_->getAngularVelocity().Ptr();
		
		// express angular velocity and betak in F basis of this body
		FastOps::transpose_mult_mat33_vec3(prFCF_Ptr,parent_ang_ptr,ang_vel);
		FastOps::transpose_mult_mat33_vec3(prFCF_Ptr,betak,s_betak);
		
		// cross( w^{k-1}, cross(w^{k-1}, \beta^{k-1}) ) {expressed in F of this body}
		FastOps::wxwxr(ang_vel, s_betak, akt_ptr+3);				
		
		// 2*cross(w^k, v^{k+1}_{k+1}u^k+1)
		akt_ptr[3] += 2*U[0]*ang_vel[1];
		akt_ptr[4] += -2*U[0]*ang_vel[0];
			
		// In this case, Akt = Akt + p^k_k \dot{u}^k
		if(this->isMotionPrescribedAndActive_){
			// Update QDot_ cache from prescribed motion
			this->PM_->setUDot(UDot);
			akt_ptr[5] += UDot[0];
		}
	} // if(Parent)
	else{
		if(this->isMotionPrescribedAndActive_){
			this->PM_->setUDot(UDot);
		}
	}
}

///////////////////////////////////////////////////////

void PrismaticZ::sweepBackwards(	const bool& isLeaf, 
					const int& ChildID,
					const Vect6& sAkt,
					const Rotation& FCF,					    
					const EOMData *eom,
					const double *betak,
					RigidBodyNode *Parent,
					ABAData *aba) const{

	if(Parent){
		Mat6x6 *Ik3 = aba->wgetIk3();
		Vect6 *Fk3 = aba->wgetFk3();			
		
		// cFk = Fk3 - Ik3*A^{k-1}_t
		this->calc_cFk(Fk3->Ptr(),Ik3->Ptr(),sAkt.Ptr(),aba->wgetcFk()->wPtr());
		
		double sIk3[36], sFk3[6];
		if(!isMotionPrescribedAndActive_){
			double triang_ik3[36],triang_cfk[6];
			this->calc_Triang_x_Ik3_TransZ(Ik3->Ptr(),triang_ik3);
			this->calc_Triang_x_cFk_TransZ(Ik3->Ptr(),aba->getcFk()->Ptr(),triang_cfk);

			FastOps::spatial_basis_shift_mat(FCF.Ptr(), triang_ik3, sIk3);
			FastOps::spatial_basis_shift_vec(FCF.Ptr(), triang_cfk, sFk3);
		}
		else{
			FastOps::spatial_basis_shift_mat(FCF.Ptr(), Ik3->Ptr(), sIk3);
			FastOps::spatial_basis_shift_vec(FCF.Ptr(), aba->getcFk()->Ptr(), sFk3);
		}

		double Ik3Child[36], Fk3Child[6];		
		this->calc_skbeta_x_Ik3_x_tskbeta(sIk3, betak, Ik3Child);
		this->calc_skbeta_x_cFk(sFk3, betak, Fk3Child);

		Parent->data_->wgetABAData()->wgetIk3()->add(Ik3Child);
		Parent->data_->wgetABAData()->wgetFk3()->add(Fk3Child);				
	}
}

///////////////////////////////////////////////////////

void PrismaticZ::sweepForward(	const RigidBodyNode *Parent,
				const int& ChildID,
				const Vect6& sAkt,
				const Rotation& FCF,
				const ABAData *aba,
				const double *betak,
				EOMData *eom,
				State& state
				 ){				

	double *UDot = state.wgetUDotForNode(this->NodeIndex_);
	const double *ik3_ptr = aba->getIk3()->Ptr();
	const double *fk3_ptr = aba->getFk3()->Ptr();
	const double *cfk_ptr = aba->getcFk()->Ptr();

	Vect6 *Ak1 = eom->wgetAk1();
	double *ak1_ptr = Ak1->wPtr();	
	
	if(Parent){
		{			
			const double *Parent_Ak1_Ptr = Parent->data_->getEOMData()->getAk1()->Ptr();
			double s_ak1[6];
			FastOps::transpose_skbeta_x_V(Parent_Ak1_Ptr, betak, s_ak1);
			FastOps::transpose_spatial_basis_shift_vec(FCF.Ptr(),s_ak1,ak1_ptr);			
		}
		
		if(!isMotionPrescribedAndActive_){
			this->calc_UDot_TransZ(ik3_ptr,ak1_ptr,cfk_ptr,UDot); // uvFlag			
			ak1_ptr[5] += UDot[0];
		}

		Ak1->add(sAkt.Ptr());				
	} // if(Parent)
	else{
		if(!isMotionPrescribedAndActive_){
			// Udot			
			UDot[0] = fk3_ptr[5]/ik3_ptr[35];
			
			// If motion is prescribed, Udot is already set in call to Prismatic::calcAKT
		}
		// Spatial acceleration of the F frame of root body.
		double ak1_tmp[]={0.0,0.0,0.0,0.0,0.0,UDot[0]};
		Ak1->copy(ak1_tmp);		
	}
	// calculate the spatial constraint force acting on this body.
	this->calc_m_cFk(fk3_ptr, ik3_ptr, ak1_ptr, eom->wgetFkc1()->wPtr());
}

///////////////////////////////////////////////////////